package com.xls.commonlibrary.util;

import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public class RSAEncrypt {

	public final static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCIQf/Q2fiurA22X+QfKyyt2d7nN+3f2vDuZrPf0bpYmGey/NaMEQ4KwldA2xgu5996UsLP3bloqm2/SPnVjpv2785Fd2Qn6Tt2kc7P0sN4pGnbxU7GECPyQJAKkz5sYizdVwb8J3758Q/lHLZqASM7zpLbLYMADP6N8lRo+PTu4QIDAQAB";

	public static void main(String[] args) throws Exception {
		//加密字符串
		String message = "df723820123456789";
		String messageEn = encrypt(message,publicKey);
		System.out.println(message + "\t加密后的字符串为:" + messageEn);
	}

	/**
	 * RSA公钥加密
	 *
	 * @param str
	 *            加密字符串
	 * @param publicKey
	 *            公钥
	 * @return 密文
	 * @throws Exception
	 *             加密过程中的异常信息
	 */
	public static String encrypt( String str, String publicKey ) throws Exception{
		//base64编码的公钥
		byte[] decoded = Base64Utils.decodeFromString(publicKey);
		RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
		//RSA加密
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
		byte[] inputArray = str.getBytes();
		int inputLength = inputArray.length;
//		System.out.println("加密字节数：" + inputLength);
		// 最大加密字节数，超出最大字节数需要分组加密
		int MAX_ENCRYPT_BLOCK = 117;
		// 标识
		int offSet = 0;
		byte[] resultBytes = {};
		byte[] cache = {};
		while (inputLength - offSet > 0) {
			if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
				offSet += MAX_ENCRYPT_BLOCK;
			} else {
				cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
				offSet = inputLength;
			}
			resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
			System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
		}
		String result = Base64Utils.encodeToString(resultBytes);
		return result;
	}

	private static byte byte_num = 8;
	public static String getEncByte(String data) {
		byte[] b_array = data.getBytes();
		byte[] n_array = new byte[b_array.length];
		int i =0 ;
		for(byte b:b_array) {
			n_array[i] = (byte) (b - byte_num);
			i++;
		}
		return new String(Base64Utils.encodeToString(n_array));
	}
}